package cn.tedu.csmall.service.impl;


import cn.tedu.csmall.exception.CoolSharkServiceException;
import cn.tedu.csmall.mapper.OrderMapper;
import cn.tedu.csmall.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.pojo.order.model.OrderTb;
import cn.tedu.csmall.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.restful.ResponseCode;
import cn.tedu.csmall.service.ICartService;
import cn.tedu.csmall.service.IOrderService;
import cn.tedu.csmall.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IStockService stockService;

    @Autowired
    private ICartService cartService;

    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        //1.减少订单中的商品的库存(要调用stock模块)
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
        stockService.reduceStockByCommodityCode(stockReduceCountDTO);

        //2.删除订单中勾选的商品
        cartService.deleteCartByUserIdAndCommodityCode(orderAddDTO.getUserId(),
                orderAddDTO.getCommodityCode());

        //3.新增订单
        OrderTb order = new OrderTb();
        BeanUtils.copyProperties(orderAddDTO, order);
        //执行mapper的新增方法
        int row = orderMapper.insertOrder(order);
        if (row == 0){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"操作数据库失败");
        }
        log.info("订单新增成功:{}", order);
    }
}
